package beans.autowire;

import cn.stimd.spring.beans.factory.ObjectFactory;
import cn.stimd.spring.beans.factory.support.DefaultListableBeanFactory;

import java.util.Map;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class UnresolvedCircleReferenceBeanFactory extends DefaultListableBeanFactory {
    @Override
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Map<String, Object> cache = (Map<String, Object>) getSingletonMutex();
        return cache.get(beanName);
    }


    @Override
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory){
        Map<String, Object> singletonObjects = (Map<String, Object>) getSingletonMutex();
        synchronized (singletonObjects){
            Object singletonObject = singletonObjects.get(beanName);
            if(singletonObject == null){
                singletonObject = singletonFactory.getObject();
                //创建Bean并加入到缓存中
                singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    }
}
